/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.proof;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.photo.ThumbnailControl;
import cn.ac.nercis.pes.community.component.spreadsheet.proof.EvalQualificationSheetView;
import cn.ac.nercis.pes.community.constant.ThumbnailSize;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.evaluation.EvaluationProofViewMapper;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.proof.ProofView;
import cn.ac.nercis.pes.model.dto.evaluation.content.proof.EvaluatorProveDTO;
import cn.ac.nercis.pes.service.evaluation.ProofService;
import cn.ac.nercis.pes.service.utils.FileManage;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 密评人员资格证明管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class PersonQualificationController implements Initializable, GlobalEventHandle, InitEvalDataLoad {
    private final static String PROVE_FILE1_NAME = "组成员成绩证明（一）";
    private final static String PROVE_FILE2_NAME = "组成员成绩证明（二）";
    private final static String EDITOR_PROVE_FILE_NAME = "编制人成绩证明";
    private final static String AUDIT_PROVE_FILE_NAME = "审核人成绩证明";
    private final static String APPROVE_PROVE_FILE_NAME = "批准人成绩证明";

    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private ListView<MenuVO> menuList;
    @FXML
    private VBox evaluatorBox;
    @FXML
    private VBox proveBox;
    @FXML
    private EvalQualificationSheetView evalQualificationView;

    @FXML
    private VBox proveFile1PictureBox;
    @FXML
    private Button addProveFile1PictureBtn;
    @FXML
    private VBox proveFile2PictureBox;
    @FXML
    private Button addProveFile2PictureBtn;
    @FXML
    private VBox editorProveFilePictureBox;
    @FXML
    private Button addEditorProveFilePictureBtn;
    @FXML
    private VBox auditProveFilePictureBox;
    @FXML
    private Button addAuditProveFilePictureBtn;
    @FXML
    private VBox approveProveFilePictureBox;
    @FXML
    private Button addApproveProveFilePictureBtn;

    private final ProofService proofService;
    private final ExecutorService executor;
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);
    private String currentSystemId;
    protected final SimpleBooleanProperty dataSaving = new SimpleBooleanProperty(false);

    public PersonQualificationController() {
        this.proofService = SpringUtils.getBean(ProofService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        saveButton.disableProperty().bind(dataSaving);
        tmpSaveButton.disableProperty().bind(dataSaving);
        addProveFile1PictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addProveFile2PictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addEditorProveFilePictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addAuditProveFilePictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));
        addApproveProveFilePictureBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-picture-icon"));

        this.initializeMenu();
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(evalQualificationView);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化密评人员资格证明信息...");
        this.currentSystemId = systemId;
        this.evalQualificationView.initialize(systemId,this::onDeleteEvaluator);
        queryEvaluator();
        loadProveFile();
        this.menuList.getSelectionModel().select(0);
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        batchSave(false,false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        batchSave(false,false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        batchSave(false,true);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        batchSave(true,false);
    }

    @FXML
    private void onAddProveFile1PictureClick(){
        addPictureClick(this.proveFile1PictureBox,addProveFile1PictureBtn,PROVE_FILE1_NAME);
    }

    @FXML
    private void onAddProveFile2PictureClick(){
        addPictureClick(this.proveFile2PictureBox,addProveFile2PictureBtn,PROVE_FILE2_NAME);
    }

    @FXML
    private void onAddEditorProveFilePictureClick(){
        addPictureClick(this.editorProveFilePictureBox,addEditorProveFilePictureBtn,EDITOR_PROVE_FILE_NAME);
    }

    @FXML
    private void onAddAuditProveFilePictureClick(){
        addPictureClick(this.auditProveFilePictureBox,addAuditProveFilePictureBtn,AUDIT_PROVE_FILE_NAME);
    }

    @FXML
    private void onAddApproveProveFilePictureClick(){
        addPictureClick(this.approveProveFilePictureBox,addApproveProveFilePictureBtn,APPROVE_PROVE_FILE_NAME);
    }

    private void initializeMenu(){
        this.menuList.setCellFactory(cf->new MenuListCell());
        this.menuList.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if(Objects.nonNull(newValue)){
                        loadContent(newValue);
                    }
                });
        this.menuList.getItems().add(new MenuVO(1,"evaluator","资格情况",""));
        this.menuList.getItems().add(new MenuVO(2,"prove","成绩证明",""));
    }

    private void loadContent(MenuVO menu){
        if(StringUtils.equals(menu.getCode(),"evaluator")){
            this.proveBox.setVisible(false);
            this.evaluatorBox.setVisible(true);
        } else {
            this.evaluatorBox.setVisible(false);
            this.proveBox.setVisible(true);
        }
    }

    private void loadProveFile() {
        LogUtils.info(log, "获取密评人员资格证明信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        //清空页面旧的图片
        CompletableFuture.supplyAsync(() -> this.proofService.findEvaluatorProve(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    loadThumbnailPicture(res.getProveFile1(),proveFile1PictureBox,addProveFile1PictureBtn,PROVE_FILE1_NAME);
                    loadThumbnailPicture(res.getProveFile2(),proveFile2PictureBox,addProveFile2PictureBtn,PROVE_FILE2_NAME);
                    loadThumbnailPicture(res.getEditorProveFile(),editorProveFilePictureBox,addEditorProveFilePictureBtn,EDITOR_PROVE_FILE_NAME);
                    loadThumbnailPicture(res.getAuditProveFile(),auditProveFilePictureBox,addAuditProveFilePictureBtn,AUDIT_PROVE_FILE_NAME);
                    loadThumbnailPicture(res.getApproveProveFile(),approveProveFilePictureBox,addApproveProveFilePictureBtn,APPROVE_PROVE_FILE_NAME);
                }))
                .exceptionally((ex) -> {
                    log.error("获取密评人员资格证明信息出错!", ex);
                    return null;
                });
    }

    private void saveProveFile(boolean realTime) {
        var prove = EvaluatorProveDTO.builder()
                .proveFile1(getPicture(this.proveFile1PictureBox))
                .proveFile2(getPicture(this.proveFile2PictureBox))
                .editorProveFile(getPicture(this.editorProveFilePictureBox))
                .auditProveFile(getPicture(this.auditProveFilePictureBox))
                .approveProveFile(getPicture(this.approveProveFilePictureBox))
                .build();
        LogUtils.info(log, "保存密评活动质量文件信息...");
        LogUtils.record(log, "请求数据：systemId:{},data:{}", this.currentSystemId, prove);
        CompletableFuture.supplyAsync(() -> this.proofService.saveEvaluatorProve(this.currentSystemId, prove))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (!res.isSuccess() && realTime) {
                        log.error("即时保存失败：{}",res.getMsg());
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存密评活动质量文件信息出错!", ex);
                    return null;
                });
    }

    private void loadThumbnailPicture(String pictureName,VBox pictureBox,Button addBtn,String name){
        if(StringUtils.isBlank(pictureName)){
            return;
        }
        File pictureFile = FileUtils.getFile(FileManage.getProveDir(this.currentSystemId),pictureName);
        if(!pictureFile.exists()){
            return;
        }
        try {
            ThumbnailControl thumbnailControl = new ThumbnailControl(pictureFile,this.page, ThumbnailSize.NORMAL_X2);
            thumbnailControl.setOnRenameEvent(this::onRenameFileChick);
            if(StringUtils.equals(name,PROVE_FILE1_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.proveFile1PictureBox,this.addProveFile1PictureBtn,PROVE_FILE1_NAME));
            }else if(StringUtils.equals(name,PROVE_FILE2_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.proveFile2PictureBox,this.addProveFile2PictureBtn,PROVE_FILE2_NAME));
            }else if(StringUtils.equals(name,EDITOR_PROVE_FILE_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.editorProveFilePictureBox,this.addEditorProveFilePictureBtn,EDITOR_PROVE_FILE_NAME));
            }else if(StringUtils.equals(name,AUDIT_PROVE_FILE_NAME)){
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.auditProveFilePictureBox,this.addAuditProveFilePictureBtn,AUDIT_PROVE_FILE_NAME));
            }else{
                thumbnailControl.setOnDeleteEvent(source->onDeleteClick(source,this.approveProveFilePictureBox,this.addApproveProveFilePictureBtn,APPROVE_PROVE_FILE_NAME));
            }
            pictureBox.getChildren().add(thumbnailControl);
            //隐藏添加图片按钮
            addBtn.setVisible(false);
        } catch (IOException ex) {
            log.error(String.format("加载%s图片文件失败：",name), ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage(String.format("载入%s图片文件失败",name))
                    .build().show();
        }
    }

    protected void onRenameFileChick(ThumbnailControl source, String oldValue, String newValue) {
        LogUtils.info(log, "执行图片文件重命名操作...");
        if (StringUtils.isBlank(newValue)) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("图片文件名不能为空！")
                    .build().show();
            return;
        }
        if (StringUtils.equals(oldValue, newValue)) {
            source.setEditMode(false);
            return;
        }
        String newFileName = newValue.concat(FileManage.getFileSuffix(source.getPictureFile().getName()));
        boolean result = source.renamePhotoFile(newFileName);
        if (!result) {
            source.renamePhotoFile(oldValue);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL)
                    .withMessage("图片文件重命名失败！")
                    .build().show();
            return;
        }
        source.setEditMode(false);
        saveProveFile(true);
    }

    private void onDeleteClick(ThumbnailControl source,VBox pictureBox,Button addBtn,String name){
        LogUtils.info(log, String.format("执行%s图片文件删除操作...",name));
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent(String.format("是否删除当前%s图片文件？",name))
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            pictureBox.getChildren().remove(source);
            removeStoreFile(source.getPictureFile());
            saveProveFile(true);
            //显示添加图片按钮
            addBtn.setVisible(true);
        });
    }

    private void removeStoreFile(@NonNull File file){
        try {
            FileUtils.delete(file);
        }catch (IOException ex){
            log.error(String.format("删除%s图文件失败：",file.getName()),ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL).withMessage("移除图文件失败")
                    .build().show();
        }
    }

    private String getPicture(VBox pictureBox){
        return pictureBox.getChildren()
                .stream()
                .filter(n->n instanceof ThumbnailControl)
                .map(n->(ThumbnailControl)n)
                .map(ThumbnailControl::getPictureFile)
                .map(File::getName)
                .findFirst()
                .orElse("");
    }

    private void addPictureClick(VBox pictureBox,Button addBtn,String name){
        LogUtils.info(log, String.format("执行%s添加图片操作...",name));
        if(pictureBox.getChildren().size()>0){
            AlertDialog alertDialog = AlertDialog.builder()
                    .withMode(AlertMode.CONFIRM)
                    .withType(AlertType.WARN)
                    .withTitle("操作提示")
                    .withContent(String.format("当前已存在%s，继续操作将进行覆盖！",name))
                    .withContainer(this.page)
                    .build();
            alertDialog.show((confirm)->{
                if(!confirm){
                    return;
                }
                addPicture(pictureBox,addBtn,name);
            });
        }else{
            addPicture(pictureBox,addBtn,name);
        }
    }

    private void addPicture(VBox pictureBox,Button addBtn,String name){
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle(String.format("选%s图片文件",name));
        fileChooser.getExtensionFilters().addAll(ControlUtils.getImageExtensionFilters());
        var currentSystem = AppStore.getCurrentSystem(this.currentSystemId);
        File selectFile = fileChooser.showOpenDialog(Objects.requireNonNull(currentSystem).getEvaluationStage());
        if(Objects.isNull(selectFile)){
            return;
        }
        try {
            File pictureFile = storePictureFile(selectFile);
            loadThumbnailPicture(pictureFile.getName(),pictureBox,addBtn,name);
            saveProveFile(true);
        }catch (IOException ex){
            log.error(String.format("添加%s图片文件出错：",name),ex);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.WARN)
                    .withMessage(String.format("添加%s图片文件失败！",name))
                    .build().show();
        }
    }

    private File storePictureFile(@NonNull File file) throws IOException {
        File saveFile = FileUtils.getFile(FileManage.getProveDir(this.currentSystemId),file.getName());
        FileManage.copyFile(file,saveFile);
        return saveFile;
    }


    private void onDeleteEvaluator(Set<String> ids){
        LogUtils.info(log, "执行删除操作...");
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("确认删除当前选中的密评人员资格情况信息吗？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            deleteEvaluator(ids);
        });
    }

    private void deleteEvaluator(final Set<String> ids) {
        LogUtils.info(log, "删除密评人员资格情况信息...");
        LogUtils.info(log, "请求数据：{}", ids);
        CompletableFuture.supplyAsync(() -> proofService.batchDeleteEvaluatorQualification(ids),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        this.evalQualificationView.getSelectionModel().clearSelection();
                        //更新表数据
                        this.queryEvaluator();
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.SUCCESS)
                                .withMessage("删除成功")
                                .build().show();
                        refreshFinishProcess(false);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL)
                                .withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("删除密评人员资格情况信息出错!", ex);
                    return null;
                });
    }

    private void batchSave(boolean realTime,boolean finish){
        if(!this.evalQualificationView.validate()){
            if(!realTime){
                MessageDialog.builder()
                        .withContainer(this.page)
                        .withType(MessageType.WARN)
                        .withMessage("以下标出的密评人员资格情况的必填信息不能为空")
                        .build().show();
            }
            return;
        }
        var evaluatorDTOList = this.evalQualificationView.getModifyData().stream()
                .map(EvaluationProofViewMapper.INSTANCE::toDTO)
                .collect(Collectors.toList());
        if (!realTime && CollectionUtils.isEmpty(evaluatorDTOList)) {
            saveProveFile(realTime);
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.SUCCESS)
                    .withMessage("保存成功")
                    .build().show();
            refreshFinishProcess(finish);
            return;
        }
        this.dataSaving.setValue(true);
        LogUtils.info(log, "批量保存密评人员资格情况信息...");
        LogUtils.record(log, "请求数据：{}", evaluatorDTOList);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.proofService.batchSaveEvaluatorQualification(evaluatorDTOList),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    this.dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        saveProveFile(realTime);
                        //更新表数据
                        this.queryEvaluator();
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                        refreshFinishProcess(finish);
                    } else {
                        if(realTime){
                            log.error("即时保存失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("批量保存密评人员资格情况信息出错!", ex);
                    return null;
                });
    }

    private void queryEvaluator() {
        LogUtils.info(log, "获取密评人员资格情况信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.proofService.findEvaluatorQualifications(this.currentSystemId),this.executor)
                .thenAccept(res -> Platform.runLater(() -> {
                    var data = res.stream()
                            .map(EvaluationProofViewMapper.INSTANCE::toVO)
                            .toList();
                    this.evalQualificationView.loadContent(data);
                }))
                .exceptionally((ex) -> {
                    log.error("获取密评人员资格情况信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL)
                            .withMessage("加载密评人员资格情况信息失败！")
                            .build().show();
                    return null;
                });
    }

    private void refreshFinishProcess(boolean finish){
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, ProofView.class);
        if(prepareView.getController() instanceof ProofController controller){
            controller.setEvalProcess(EvaluationModule.PROOF_PERSON, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }

}